#define _CRT_SECURE_NO_WARNINGS 1
#include"SList.h"

//打印数据
void SLNodePrint(SLNode* phead)
{
	SLNode* cur = phead;
	while (cur != NULL)
	{
		printf("%d->",cur->data );
		cur = cur->next;
	}
	printf("NULL");
}

//新创建一个结构体空间，存放新输入的数据
SLNode* BuySLNode(SListNodeType x)
{
	SLNode* newnode = (SLNode*)malloc(sizeof(SLNode));
	if (newnode == NULL)
	{
		perror("malloc fail");
		exit(-1);
	}
	newnode->data = x;
	newnode->next = NULL;
	return newnode;
}

//在链表最前端插入一个数据
void SLNodePushFront(SLNode** pphead, SListNodeType x)
{
	assert(pphead);
	SLNode* newnode=BuySLNode(x);
	newnode->next = *pphead;
	*pphead = newnode;
}

//在链表最后端插入一个数据
void SLNodePushBack(SLNode** pphead, SListNodeType x)
{
	SLNode* newnode = BuySLNode(x);
	/*1.整个链表为空*/
	if (*pphead == NULL)
	{
		*pphead = newnode;
	}
	/*2.链表不为空*/
	else
	{
		SLNode* cur = *pphead;
		while (cur->next != NULL)
		{
			cur = cur->next;
		}
		newnode = cur->next;
	}
}
//删除链表最后端的数据
void SLNodePopBack(SLNode** pphead)
{
	/*1.链表为空*/
	if ((*pphead)->next == NULL)
	{
		free(*pphead);
		*pphead = NULL;
	}
	/*2.链表不为空*/
	else
	{
		SLNode* cur = *pphead;
		SLNode* prev = NULL;
		while (cur->next != NULL)
		{
			prev = cur;
			cur = cur->next;
		}
		prev->next = NULL;
		free(cur);
		cur = NULL;
	}
}

//删除链表最前端的数据
void SLNodePopFront(SLNode** pphead)
{
	assert(pphead);
	SLNode* det = *pphead;
	*pphead = (*pphead)->next;
	free(det);
	det = NULL;
}

void SListDestory(SLNode** pphead)
{
	assert(pphead);
	SLNode* cur = *pphead;
	while (cur != NULL)
	{
		SLNode* next = cur->next;
		free(cur);
		cur = next;
	}
	*pphead = NULL;
}

//在链表中查找某个数据
SLNode* SListFind(SLNode* phead, SListNodeType x)
{
	SLNode* cur = phead;
	while (cur)
	{
		if (cur->data == x)
		{
			return cur;
		}
		cur = cur->next;
	}
	return NULL;
}

//在pos前插入一个数据
void SListInsert(SLNode** pphead, SLNode* pos, SListNodeType x)
{
	assert(pphead);
	assert(pos);
	if (pos == *pphead)
	{
		SLNodePushFront(*pphead, x);
	}
	else
	{
		SLNode* cur = *pphead;
		SLNode* newnode = BuySLNode(x);
		while (cur->next != pos)
		{
			cur = cur->next;
		}
		cur->next=newnode;
		newnode->next = pos;
	}
}

// 在pos后面插入
void SListInsertAfter(SLNode* pos, SListNodeType x)
{
	assert(pos);
	SLNode* newnode = BuySLNode(x);
	newnode->next = pos->next;
	pos->next = newnode;
}